<template>
  <v-menu
    v-model="dateMenu"
    :close-on-content-click="false"
    transition="scale-transition"
    offset-y
    :max-width="width"
    :min-width="width"
  >
    <template v-slot:activator="{ on, attrs }">
      <v-text-field
        v-model="dateRangeText"
        prepend-icon="mdi-calendar"
        outlined
        :label="label"
        v-bind="attrs"
        v-on="on"
        dense
        readonly
      ></v-text-field>
    </template>
    <v-date-picker
      v-model="localDateRange"
      no-title
      show-adjacent-months
      range
      @input="onFinishDatePicker"
    ></v-date-picker>
  </v-menu>
</template>

<script>

  export default {
    name: "DateRangePicker",
    model: {
      prop: "dateRange",
      event: "change",
    },

    props: {
      dateRange: {
        // iso格式的日期字符串
        type: Array,
        default: () => [],
      },

      width: {
        type: Number,
        required: false,
        default: 300,
      },
      label: {
        type: String,
        required: false,
        default: "选择日期范围",
      },
    },

    data() {
      return {
        dateMenu: false,
        localDateRange: [],
      }
    },

    computed: {
      dateRangeText() {
        return this.localDateRange.join(" ~ ")
      },
    },

    mounted() {
        if (this.dateRange && this.dateRange.length == 2) {
          this.localDateRange = [...this.dateRange]
        } else {
          this.localDateRange = []
        }
    },

    watch: {
      dateRange(val) {
        if (val && val.length == 2) {
          this.localDateRange = [...val]
        } else {
          this.localDateRange = []
        }
      },
    },

    methods: {
      onFinishDatePicker() {
        let daterange = [...this.localDateRange]
        if(daterange && daterange.length == 2){
          // 按起始排个序
          const first = this.localDateRange[0]
          const second = this.localDateRange[1]
          first > second? daterange = [second, first] : daterange = [first, second]
          this.localDateRange = daterange
        }
        this.$emit("change", daterange)
      },
    },
  }
</script>
